package cn.touna.jss.modules.custom.carmodel.synctask;

import javax.crypto.*;
import javax.crypto.spec.DESedeKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;

/**
 * 为精真估接口提供加解密
 */
public class EncryptUtil {

    /**
     * MD5值计算<p>
     * MD5的算法在RFC1321 中定义:
     * 在RFC 1321中，给出了Test suite用来检验你的实现是否正确：
     * MD5 ("") = d41d8cd98f00b204e9800998ecf8427e
     * MD5 ("a") = 0cc175b9c0f1b6a831c399e269772661
     * MD5 ("abc") = 900150983cd24fb0d6963f7d28e17f72
     * MD5 ("message digest") = f96b697d7cb7938d525a2f31aaf161d0
     * MD5 ("abcdefghijklmnopqrstuvwxyz") = c3fcd3d76192e4007dfb496cca67e13b
     *
     * @param str 源字符串
     * @return md5值
     */
    public final static byte[] MD5(String str) {
        try {
            byte[] res = str.getBytes("UTF-8");
            MessageDigest mdTemp = MessageDigest.getInstance("MD5".toUpperCase());
            mdTemp.update(res);
            byte[] hash = mdTemp.digest();
            return hash;
        } catch (Exception e) {
            return null;
        }
    }


    // 加密后解密
    public static String JM(byte[] inStr) {
        String newStr = new String(inStr);
        char[] a = newStr.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char) (a[i] ^ 't');
        }
        String k = new String(a);
        return k;
    }


    /**
     * BASE64加密
     *
     * @param key
     * @return
     * @throws Exception
     */
    public static String BASE64Encrypt(byte[] key) {
        String edata = null;
        try {
            edata = Base64.getEncoder().encodeToString(key).trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return edata.replaceAll("\r|\n", "");
    }


    /**
     * BASE64解密
     *
     * @param data key
     * @return
     * @throws Exception
     */
    public static byte[] BASE64Decrypt(String data) {
        if (data == null) return null;
        byte[] edata = null;
        try {
            edata = Base64.getDecoder().decode(data);
            return edata;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param key 24位密钥
     * @param str 源字符串
     * @return
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidKeyException
     * @throws UnsupportedEncodingException
     * @throws InvalidKeySpecException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    public static byte[] DES3Encrypt(String key, String str) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnsupportedEncodingException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException {

        byte[] newkey = key.getBytes();

        SecureRandom sr = new SecureRandom();

        DESedeKeySpec dks = new DESedeKeySpec(newkey);

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");

        SecretKey securekey = keyFactory.generateSecret(dks);

        Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");

        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

        byte[] bt = cipher.doFinal(str.getBytes("utf-8"));

        return bt;
    }


    /**
     * 解密
     *
     * @param edata
     * @param key
     * @return
     * @throws Exception
     */
    public static String DES3Decrypt(byte[] edata, String key) {
        String data = "";
        try {
            if (edata != null) {
                byte[] newkey = key.getBytes();
                DESedeKeySpec dks = new DESedeKeySpec(newkey);
                SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
                SecretKey securekey = keyFactory.generateSecret(dks);
                Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
                cipher.init(Cipher.DECRYPT_MODE, securekey, new SecureRandom());
                //String newData = new String(edata);
//				if (!newData.endsWith("=")){
//					data = URLDecoder.decode(newData,"utf-8");
//				}
                byte[] bb = cipher.doFinal(edata);
                data = new String(bb, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 生成请求接口签名
     * @param partnerId
     * @param message
     * @param key
     * @return
     */
    /*
    public static String getSignature(String operate, String partnerId, String key, String message){
		String body = EncryptUtil.getBodyEncryption(key, message);
		String sequenceId = StringUtils.getData();
		StringBuffer str = new StringBuffer();
		str.append(sequenceId);
		str.append(partnerId);
		str.append(operate);
		str.append(body);
		str.append(key);
		String sig = BASE64Encrypt(MD5(str.toString()));
		SendRequest sendRequest = new SendRequest();
		sendRequest.setSequenceId(sequenceId);
		sendRequest.setPartnerId(partnerId);
		sendRequest.setOperate(operate);
		sendRequest.setSign(sig);
		sendRequest.setBody(body);
		return new GsonBuilder().disableHtmlEscaping().create().toJson(sendRequest);
	}*/

    /**
     * 加密请求报文体
     *
     * @param body
     * @return
     */
    public static String getBodyEncryption(String key, String body) {
        //ToBase64(3DES(Body明文)
        try {
            return BASE64Encrypt(DES3Encrypt(key, body));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密返回的报文体body
     *
     * @param body
     * @param key
     * @return
     */
    public static String getDecodeBodyMessage(String body, String key) {
        //Decrypt3DES(FromBase64 (Body密文)
        return DES3Decrypt(BASE64Decrypt(body), key);
    }

    /**
     * 加密返回报文的签名
     *  MsgCode+Msg+Body密文+Key)
     * @return
     */
    /*public static boolean  getSigReturnMessage(ReturnCarVinMessage returnCarVinMessage, String key){
        StringBuffer str = new StringBuffer();
		str.append(returnCarVinMessage.getMsgCode());
		str.append(returnCarVinMessage.getMethod());
		str.append(returnCarVinMessage.getBody());
		str.append(key);
		if(BASE64Encrypt(MD5(str.toString())).equals(returnCarVinMessage.getSign())){
			return true;
		}
		return false;
	}*/


}
